<template>
  <div class="h-all flex auto fd-c">
    <div class="fs-20 pp10 flex nodarg ra-10 mr10 ai-c flex-1">
      <div class="rel h-all w-all">
        <textarea placeholder="输入或复制英语句子 或 文章" spellcheck="true" v-model="info.word" maxlength="1000" class="w-all bc-t fs-28 lh-40 pp15 eye-bg ra-10 b-0 input glass-card h-all"></textarea>
        <div class="abs al25 ab15 ar15 flex ai-c">
          <tooltip placement="top" space="6" class="flex-line fs-14" content="截屏识别文字">
            <!-- <span @click="info.isOpenAi=true" class="fc-aa nodarg fs-28 fb iconfont icon-ai2 hand pp5"></span> -->
            <span @click="toCapture" class="fc-aa nodarg fs-24 fb iconfont icon-quyujieping hand pp5"></span>
          </tooltip>
          <tooltip placement="top" space="6" class="flex-line fs-14" content="AI生成文章">
            <span @click="info.isOpenAi=true" class="fc-aa nodarg fs-28 fb iconfont icon-ai2 hand pp5"></span>
          </tooltip>
          <span class="flex-1"></span>
          <div @click="onAudio" class="btns btn-1 pl15 pr15 fs-16 flex ai-c jc-c h-36 ra-5">开始生成</div>
          <!-- <div class="btns btn-1 pl15 pr15 fs-16 flex ai-c ml10 jc-c h-36 ra-5">收起</div> -->
          <span class="ml20">{{info.word.length||0}}/1000</span>
        </div>
      </div>
    </div>
  </div>
  <div v-if="info.isModel" class="fixed flex ai-c sha-card zi-2000 jc-c at0 al0 ab0 ar0 ba-f2">
    <div class="fixed flex ai-c sha-card jc-c at0 al0 ab0 ar0 ba-f2">
      <div style="width:92%;background-color:#14261ee3; padding: 18px 10px 18px 18px; height: 93%;" class="mt20 rel ra-10">
        <div class="flex-line abs zi-140 nodarg al30 at20">
          <Switch v-model="query.isFast" class="fs-18 fc-fff" @change="changeAudio" open="正常,1,#008d1a" close="慢速,2,#ff9900" show></Switch>
        </div>
        <span @click.stop="btnClose" class="iconfont hand nodarg icon-bg-close zi-2000 fc-fff fs-30 abs at10 ar10"></span>
        <span @click="toReading()" v-if="!info.isPlay" class="iconfont icon-bofang1 hand abs nodarg zi-120 fc-success fs-50 ar90 at30"></span>
        <span @click="stopRead()" v-else class="iconfont icon-bofang hand abs nodarg zi-120 fc-danger fs-50 at30 ar90"></span>
        <div class=" w-all  mb10 nodarg custom-scrollbar zi-100  pp5 h-all auto ">

          <div class="flex fd-c ai-c mt7 jc-c" v-for="item in info.curr.sentences">
            <!-- <span @click="toReading(item.en,item)" class="fc-fff nodarg hand fs-26">{{item.en}} <span class="iconfont icon-ting fs-25 fc-pri "></span></span> -->
            <div :class="{'bc-00fc102b ra-6 pl15 pt5 pb5 pr15':item.select}" class="flex pl40 pr40 ai-c fw">
              <span @click="onWordPlay(w.text)" v-copy="w.text" class="mr9 fc-fff nowarp nodarg hand fs-26" :class="{'fc-danger':w.select}" v-for="w in item.words">{{w.text}}</span>
              <span @click="onWordPlay(item.text,1,true)" class="iconfont icon-ting hand fs-29 fc-danger"></span>
            </div>
            <span class="fc-aa fs-19">{{item.cns}}</span>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div v-if="info.isOpenAi" class="fixed flex ai-c sha-card jc-c at0 al0 ab0 ar0 ba-f2">
    <div @click="info.isOpenAi=false" class="fixed flex ai-c fd-c sha-card jc-c at0 al0 ab0 ar0 ba-f2">
      <div @click.stop style="background-color:#14261ee3; padding: 18px 10px 18px 18px;" class="pp30 w-600 rel ra-10">
        <input v-model="info.aiWord" class="w-all h-70 ra-10 bc-f5 pp10 fs-20" placeholder="请输入如：大海、上学等 三年级上英文短语" type="text">
        <div @click="onOpenai" class=" btn btn-primary pl15 pr15 fs-16 w-all flex ai-c mt15 jc-c h-46 ra-5">生成文章</div>
      </div>
    </div>
  </div>
</template>

<script setup lang='ts'>
import { reactive, ref, inject } from 'vue';
import yy from '@lib/mixin';
const spell = require('spell-checker-js')
spell.load('en')
import useStore from '../../store';
const st = useStore();
const reload = inject('reload') as () => void;
const info = reactive({
  word: "",
  aiWord: "",
  list: [],
  playAudio: null,
  curr: null,
  isPlay: false,
  interval: null,
  isPause: false,
  isModel: false,
  isOpenAi: false
})

const query = reactive({
  isFast: 1,//慢，正常
})

function btnClose() {
  info.playAudio && info.playAudio.pause();
  info.isPause = true;
  info.isPlay = false;
  info.isModel = false;
  // reload();
}

function onOpenai() {
  if (info.aiWord.length < 4) {
    yy.msg.error('请输入短文规则如：小学三年级英语短文');
    return;
  }

  // 生成一篇三年级英语晨读短文
  yy.spinner.show()
  let list = [{ role: "system", content: `返回 JSON 格式。内容格式为{title:'',content:''} 内容里不需要title 且内容只能为文本 生成英语文章 无需序号` }]
  list.push({ role: 'user', content: info.aiWord })
  st.invoke('deepseek', { list, isJson: true }).then(res => {
    console.log(res);

    yy.spinner.close();
    info.isOpenAi = false;
    info.word = `${JSON.parse(res).title} . ${JSON.parse(res).content}`
  })
}

function changeText() {
  info.word = info.word.split('.')
    .map(s => s.trim())
    .filter(s => s.length > 0)
    // 2. 修复逗号问题
    .map(s => {
      // 修复单词被逗号错误分割的情况（如 co,mputer → computer）
      let fixedSentence = s.replace(/([a-zA-Z]),([a-zA-Z])/g, '$1$2');
      // 剩余逗号替换为空格（如 "reading book,playing" → "reading book playing"）
      fixedSentence = fixedSentence.replace(/,/g, ' ');
      // 合并多余空格
      fixedSentence = fixedSentence.replace(/\s+/g, ' ').trim();
      // 首字母大写（确保每句开头正确）
      fixedSentence = fixedSentence.charAt(0).toUpperCase() + fixedSentence.slice(1);
      return fixedSentence;
    }).join('. ')
}

function toCapture() {
  yy.spinner.show({ type: 5, message: '提取文字中...' })
  st.invoke('capture-image', { orc: true }).then(res => {
    console.log(res);
    yy.spinner.close()
    if (res.text.code == 100) {
      info.word = res.text.data.map(v => v.text).join('').split('.')
        .map(s => s.trim())
        .filter(s => s.length > 0)
        // 2. 修复逗号问题
        .map(s => {
          // 修复单词被逗号错误分割的情况（如 co,mputer → computer）
          let fixedSentence = s.replace(/([a-zA-Z]),([a-zA-Z])/g, '$1$2');
          // 剩余逗号替换为空格（如 "reading book,playing" → "reading book playing"）
          // 合并多余空格
          fixedSentence = fixedSentence.replace(/\s+/g, ' ').trim();
          // 首字母大写（确保每句开头正确）
          fixedSentence = fixedSentence.charAt(0).toUpperCase() + fixedSentence.slice(1);
          return fixedSentence;
        }).join('. ')
    }
  }).catch(res => {
    console.log(res)
    yy.spinner.close()
  })
}

function changeAudio(v) {
  st.ttsConfig.rate = query.isFast == 2 ? "0.35" : 1;
  if (info.playAudio) {
    info.playAudio.pause();
    info.playAudio = null;
  }
  onAudio()
}

function onAudio() {
  if (info.curr && info.word.length) {
    info.isModel = true;
    return;
  }
  if (/[\u4e00-\u9fa5]/.test(info.word)) {
    yy.msg.error('短文中存在中文');
    return;
  }
  let errorWord = spell.check(info.word);
  let title = info.word.split('.')[0].split(',')[0];
  if (errorWord.length) {
    yy.msg.confirm(`疑似错误单词：${errorWord.toString()} 请修正`, res => {
      if (res == 'ok') {
        yy.spinner.show();
        st.speek(info.word, { auto: false, word: true, line: true, fileName: `freedom`, isFile: true, file: { title: title, fileUrl: st.fileUrl } }).then(res => {
          // item.loading = false;
          info.isModel = true;
          yy.spinner.close();
          console.log(res);

          info.curr = { ...res };
        })
      }
    })
  } else {
    yy.spinner.show();
    st.speek(info.word, { auto: false, word: true, line: true, fileName: `freedom`, isFile: true, file: { title: title, fileUrl: st.fileUrl } }).then(res => {
      // item.loading = false;
      yy.spinner.close();
      info.isModel = true;
      console.log(res)
      info.curr = { ...res };
    })
  }
}


function toReading(line) {
  if (line) {
    toPlay(info.curr.url, line)
  } else {
    toPlay(info.curr.url)
  }
}

function setWordHight(next = true) {
  if (!next && info.playAudio) return;
  info.curr?.sentences.forEach(item => {
    item.select = false;
    item.words.forEach(v => v.select = false)
  })
  // 高亮句子
  info.curr?.sentences.forEach(item => {
    if (info.playAudio.currentTime >= item.start && info.playAudio.currentTime <= item.end) {
      item.select = true;
      // 句子高亮
      item.words.forEach(v => {
        if (info.playAudio.currentTime >= v.start && info.playAudio.currentTime <= v.end) {
          v.select = true;
        } else {
          v.select = false;
        }
      })
    }
  })
}

function toPlay(url, line) {
  if (!info.isPause) {
    info.playAudio = new Audio(url);
  }
  info.playAudio.play()
  info.isPlay = true;
  const currentTime = 0;
  info.isPause = false;

  info.playAudio.addEventListener('timeupdate', e => {
    let count = 5
    let timer = setInterval(function () {
      if (count == 0) {
        clearInterval(timer)
      } else {
        setWordHight()
        count--;
      }
    }, 50)
  })

  info.playAudio.addEventListener('ended', () => {
    info.isPause = false;
    info.isPlay = false;
    info.curr.sentences.forEach(item => {
      item.select = false;
      item.words.forEach(v => v.select = false)
    })
    if (info.playAudio) {
      info.playAudio.pause();
      info.playAudio = null;
    }
  })
}

</script>

<style lang='less'>
</style>